var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require("cors");
var app = express();
const bodyParser = require('body-parser');
const  verifyAuthToken  = require('./routes/tokens');
// 加载环境变量
require('dotenv').config();



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());



// 配置 CORS 中间件
app.use(cors({
  origin:[ 'http://localhost:5173','http://localhost:5174'], // 允许的前端域名
  methods: ['GET', 'POST', 'PUT', 'DELETE','OPTIONS'], // 允许的 HTTP 方法
  credentials: true // 允许发送凭据（如 cookies）
}));


// 静态文件中间件
app.use('/uploads', express.static('uploads'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/files', express.static(path.join(__dirname, 'files')));

//token双

app.use(verifyAuthToken)



// 路由
var mainRouter = require('./routes/main');
app.use('/main', mainRouter);

var xzxRouter = require('./routes/xzx');
app.use('/xzx', xzxRouter);

var lxRouter = require('./routes/lx');
app.use('/lx', lxRouter);

var lxRouter = require('./routes/cry');
app.use('/cry', lxRouter);
var wwzRouter = require('./routes/wwz');
app.use('/wwz', wwzRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;